const Log = require('./log.js')
const { sqLogin, getIsLogin } = require('./user.js')

const PAGES = require('../utils/pages.js')
const HTTP = function (options) {
  // 如果传递进来的参数中没有相应的方法，那么给其赋值一个空的函数
  const noop = function () { }

  // 获取参数相应的方法
  const success = options.success || noop
  const fail = options.fail || noop
  const complete = options.complete || noop

  // 构造成功和失败的回调函数
  const callSuccess = function () {
    success.apply(null, arguments)
    complete.apply(null, arguments)
    if (options.showLoading) {
      Log.info("http hideloading")
      wx.hideLoading()
    }
  }
  const callFail = function (err) {
    Log.log(err)
    fail.call(null, {
      msg: err.msg || "服务器连接失败，请稍后重试～"//res.errMsg
    })
    complete.call(null, err)
    if (options.showLoading) {
      Log.info("http hideloading")
      wx.hideLoading()
    }
  }

  // url不能为空
  if (!options.url) {
    callFail()
    return
  }


  if (options.showLoading) {
    Log.info("http showloading")
    wx.showLoading()
  }

  // 发出请求
  wx.request({
    url: options.url,
    data: options.data || null,
    header: options.header || {
      'content-type': 'application/json',
      'token': options.userToken,
      'lang': (wx.getStorageSync('Language') || 'cn') == 'en' ? 'en' : 'cn'
      // Authorization: 'Bearer ' + wx.getStorageSync("user_token")
    },
    method: options.method || 'POST',
    success: function (res) {
      Log.log('===============request===============')
      Log.log('url:' + options.url)
      Log.log('data:')
      Log.log(options.data)
      Log.log('=================response===================')
      Log.log("url:" + options.url)
      Log.log("data:")
      Log.log(res.data)
      Log.log('========================================')

      let response = res.data
      // 业务判断
      if (response.IsSuccess) {
        // 返回业务数据
        callSuccess(response)
      } else {
        // 返回错误信息
        if (response.Code == -104 || response.Code == -101) {
          wx.navigateTo({
            url: PAGES.index + "?isShowLogin=1",
          })
        }

        callFail({
          msg: response.Message//res.errMsg
        })
      }

    },
    fail: function (res) {
      Log.log('---------response-fail---------------')
      Log.log("url:" + options.url)
      Log.log(res)
      Log.log('========================================')
      callFail({
        msg: "服务器异常，请稍后重试～"//res.errMsg
      })
    }
  })

  Log.log('userToken:' + options.userToken)
}

module.exports = {
  HTTP
}